import { v4 as uuidv4 } from 'uuid';

import qs from 'qs';

/**
 * 存储localStorage
 */
export const commonSetLocalStorage = (name: string, content: string) => {
	if (!name) return;
	if (typeof content !== 'string') {
		content = JSON.stringify(content);
	}
	window.localStorage.setItem(name, content);
}

/**
 * 获取localStorage
 */
export const commonLocalStorage = (name: string) => {
	if (!name) return;
	return window.localStorage.getItem(name);
}

/**
 * 删除localStorage
 */
export const commonRemoveLocalStorage = (name: string) => {
	if (!name) return;
	window.localStorage.removeItem(name);
}

/**
 * 金额转千分位保留两位小数
 */
// export const commonToThousandsMoney = (num: number) => {
//   let numStr = num.toString();
//   let result = '', counter = 0;
//   for (let i = numStr.length - 1; i >= 0; i--) {
//     counter++;
//     result = numStr.charAt(i) + result;
//     if (!(counter % 3) && i != 0) {
//       result = ',' + result;
//     }
//   }
//   return result;
// }
export const commonToThousands = (num: number) => {
	// let numStr = num.toString();
	// let result = '', counter = 0;
	// for (let i = numStr.length - 1; i >= 0; i--) {
	// 	counter++;
	// 	result = numStr.charAt(i) + result;
	// 	if (!(counter % 3) && i != 0) {
	// 		result = ',' + result;
	// 	}
	// }
	return formatNumberWithCommas(num);
}

export function formatNumberWithCommas(value: number) {
  // 保留两位小数
  let num = Number(value).toFixed(2);

  // 使用正则表达式插入千分位逗号
  let [integer, decimal] = num.split('.');
  integer = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',');

  // 拼接整数部分和小数部分
  return `${integer}.${decimal}`;
}

/**
 * 生成UUID
 */
export const createUUID = () => {
	return uuidv4().replace(/-/g,"")
}


/**
 * 判断页面是否是在iframe里面
 */
export const isInIframe = () => {
	return (window.self !== window.top);
}


/**
 * 清除列表缓存
 */
export const cleanLocalStorage = () => {
  const keys = Object.keys(localStorage);
  keys.forEach(key => {
    if (key.includes('list')) {
      localStorage.removeItem(key);
    }
  })
}

/**
 * 格式化地址栏参数
 */
export const queryURL = (data:any) => {
  const url = data || window.location.href;
  const arr1 = url.split("?");
  if (arr1.length > 1) {
    const paramsString = arr1[1];
    const params = qs.parse(paramsString);
    return params;
  }
  return {};
};

/**
 * 限制数字输入框不能输入字母e
 */
export const limitInput = (e: any) => {
  if (e.key === 'e') {
    e.preventDefault();
  }
}
